<?php

namespace app\admin\controller;

use think\Validate;
use think\Db;
use app\models\{PlatClass, Order as Orders, Goods, GoodsSpec, User, OrderGoods, LorderGoods, Lorder};

class Order extends Base
{

    public function list()
    {
        $list = (new Orders())->where(['shouhou' => 1, 'status' => [1, 2, 3, 4, 5]])->order(['id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('ordersn|name|mobile|remark', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['review'])) {
            $list = $list->where('review', $data['review']);
        }
        if (!empty($data['starttime'])) {
            $endtime = !empty($data['endtime']) ? $data['endtime'] : date('Y-m-d H:i:s');
            $list = $list->whereBetweenTime('created', $data['starttime'], $endtime);
        }
        $list = $list->paginate(10);
        foreach ($list as $lists) {
            $lists['status_text'] = $lists->status_text;
            $lists['review_text'] = $lists->review_text;
        }
        return view(null, [
            'list' => $list
        ]);
    }

    public function rpay()
    {
        $list = (new Orders())->where(['review' => [2, 3]])->order(['id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('ordersn|name|mobile|remark', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['review'])) {
            $list = $list->where('review', $data['review']);
        }
        if (!empty($data['starttime'])) {
            $endtime = !empty($data['endtime']) ? $data['endtime'] : date('Y-m-d H:i:s');
            $list = $list->whereBetweenTime('created', $data['starttime'], $endtime);
        }
        $list = $list->paginate(10);
        foreach ($list as $lists) {
            $lists['status_text'] = $lists->status_text;
            $lists['review_text'] = $lists->review_text;
            $lists['images'] = json_decode($lists['images'], true);
        }
        return view(null, [
            'list' => $list
        ]);
    }

    public function list1()
    {
        $list = (new Orders())->where(['shouhou' => 1, 'status' => [3, 4]])->order(['id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('ordersn|name|mobile|remark', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['review'])) {
            $list = $list->where('review', $data['review']);
        }
        if (!empty($data['starttime'])) {
            $endtime = !empty($data['endtime']) ? $data['endtime'] : date('Y-m-d H:i:s');
            $list = $list->whereBetweenTime('created', $data['starttime'], $endtime);
        }
        $list = $list->paginate(10);
        foreach ($list as $lists) {
            $lists['status_text'] = $lists->status_text;
            $lists['review_text'] = $lists->review_text;
        }
        return view(null, [
            'list' => $list
        ]);
    }


    public function list2()
    {
        $list = (new Orders())->where(['shouhou' => 2, 'status' => [1, 2, 3, 4]])->order(['id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('ordersn|name|mobile|remark', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['review'])) {
            $list = $list->where('review', $data['review']);
        }
        if (!empty($data['starttime'])) {
            $endtime = !empty($data['endtime']) ? $data['endtime'] : date('Y-m-d H:i:s');
            $list = $list->whereBetweenTime('created', $data['starttime'], $endtime);
        }
        $list = $list->paginate(10);
        foreach ($list as $lists) {
            $lists['status_text'] = $lists->status_text;
            $lists['review_text'] = $lists->review_text;
        }
        return view(null, [
            'list' => $list
        ]);
    }

    public function listdetail()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'user_id' => 'require',
                'name' => 'require',
                'mobile' => 'require',
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'address' => 'require',
                'goodsid' => 'require',
            ], [
                'user_id.require' => '下单用户不能为空',
                'name.require' => '收货人不能为空',
                'province.require' => '省份不能为空',
                'city.require' => '城市不能为空',
                'area.require' => '区域不能为空',
                'address.require' => '地址不能为空',
                'goodsid.require' => '商品不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $goods = $data['goodsid'];
            $order = [
                'user_id' => $data['user_id'],
                'ordersn' => reordersn(new Orders()),
                'name' => $data['name'],
                'mobile' => $data['mobile'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'address' => $data['address'],
                'total' => 0,
                'remark' => $data['remark'] ?? '',
                'total' => 0,
                'ptotal' => 0
            ];
            $ordergoods = [];
            foreach ($goods as $good) {
                $goodspec = (new Goods())->where('g.isdel', 1)->where('g.id', $good['id'])->alias('g')->join('GoodsSpec gs', 'gs.goodid = g.id')->field('g.*,gs.name,gs.price,gs.stock,gs.unmit,gs.starbuy,gs.id as specid')->find();
                if (!empty($goodspec) && $good['number'] > 0) {
                    $order['ptotal'] += $good['price'] * $good['number'];
                    $ordergoods[] = [
                        'ordersn' => $order['ordersn'],
                        'classid' => $goodspec['classid'],
                        'goodsid' => $goodspec['id'],
                        'goodspecid' => $goodspec['specid'],
                        'title' => $goodspec['title'],
                        'images' => $goodspec['images'] ?? '',
                        'name' => $goodspec['name'],
                        'number' =>  $good['number'],
                        'unmit' => $goodspec['unmit'],
                        'price' =>   $good['price'],
                        'total' => floor($good['number'] * $good['price'] * 100) / 100
                    ];
                }
            }
            $order['total'] = $order['ptotal'];
            if (count($ordergoods) < 1 || count($order) < 1) {
                return json(['status' => 1, 'msg' =>  '商品下架或未填写商品数量']);
            }
            Db::startTrans();
            try {
                (new Orders())->allowfield(true)->save($order);
                (new OrderGoods())->allowfield(true)->saveAll($ordergoods);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'msg' =>  '操作失败，请重试' . $e->getMessage()]);
            }
            return json(['status' => 0, 'msg' =>  '操作成功']);
        } else {
            //客户列表
            return view(null, [
                'user' => (new User())->select()
            ]);
        }
    }

    public function list_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            switch ($data['type']) {
                case '1':
                    $validate = new Validate([
                        'id' => 'require',
                        'goodsid' => 'require',
                    ], [
                        'id.require' => 'ID不能为空',
                        'goodsid.require' => '商品不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        return json(['status' => 1, 'msg' =>  $validate->getError()]);
                    }
                    //查找订单
                    $order = (new Orders())->where('id', $data['id'])->find();
                    if (empty($order) || $order['status'] != 1) {
                        return json(['status' => 1, 'msg' =>  '订单不存在或当前状态不可修改商品信息']);
                    }
                    $goods = $data['goodsid'];
                    $total = 0;
                    $ordergoods = [];
                    foreach ($goods as $good) {
                        $goodspec = (new Goods())->where('g.isdel', 1)->where('g.id', $good['id'])->alias('g')->join('GoodsSpec gs', 'gs.goodid = g.id')->field('g.*,gs.name,gs.price,gs.stock,gs.unmit,gs.starbuy,gs.id as specid')->find();
                        if (!empty($goodspec) && $good['number'] > 0) {
                            $total += $good['price'] * $good['number'];
                            $ordergoods[] = [
                                'ordersn' => $order['ordersn'],
                                'classid' => $goodspec['classid'],
                                'goodsid' => $goodspec['id'],
                                'goodspecid' => $goodspec['specid'],
                                'title' => $goodspec['title'],
                                'images' => $goodspec['images'] ?? '',
                                'name' => $goodspec['name'],
                                'number' =>  $good['number'],
                                'unmit' => $goodspec['unmit'],
                                'price' =>   $good['price'],
                                'total' => floor($good['number'] * $good['price'] * 100) / 100
                            ];
                        }
                    }
                    if (count($ordergoods) < 1) {
                        return json(['status' => 1, 'msg' =>  '商品下架或删除，请重新选择']);
                    }
                    Db::startTrans();
                    try {
                        (new OrderGoods())->where(['ordersn' => $order['ordersn']])->delete();
                        (new Orders())->where('id', $data['id'])->update(['total' => $total, 'ptotal' => $total]);
                        (new OrderGoods())->allowfield(true)->saveAll($ordergoods);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return json(['status' => 1, 'msg' =>  '操作失败，请重试' . $e->getMessage()]);
                    }
                    break;
                case '2':
                    $validate = new Validate([
                        'id' => 'require',
                        'images' => 'require',
                    ], [
                        'id.require' => 'ID不能为空',
                        'images.require' => '付款凭证不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        return json(['status' => 1, 'msg' =>  $validate->getError()]);
                    }
                    //查找订单
                    $order = (new Orders())->where('id', $data['id'])->find();
                    if (empty($order)) {
                        return json(['status' => 1, 'msg' =>  '订单不存在']);
                    }
                    $images = array_filter($data['images']);
                    if (count($images) <= 0) {
                        return json(['status' => 1, 'msg' =>  '请先上传或选择付款凭证']);
                    }
                    $images = json_encode($images, true);
                    Db::startTrans();
                    try {
                        (new Orders())->where('id', $data['id'])->update(['review' => 3, 'images' => $images]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return json(['status' => 1, 'msg' =>  '操作失败，请重试' . $e->getMessage()]);
                    }
                    break;

                case '3':
                    $validate = new Validate([
                        'id' => 'require',
                        'status' => 'require',
                    ], [
                        'id.require' => 'ID不能为空',
                        'status.require' => '状态不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        return json(['status' => 1, 'msg' =>  $validate->getError()]);
                    }
                    foreach ($data['id'] as $id) {
                        //查找订单
                        $order = (new Orders())->where('id', $id)->find();
                        if (empty($order) || $order['status'] == 5 || $order['status'] == 6) {
                            continue;
                        }
                        if ($data['status'] != 6 && abs($order['status'] - $data['status']) != 1) {
                            continue;
                        }
                        if ($data['status'] < $order['status'] && !empty($data['all'])) {
                            continue;
                        }
                        $rorder = [];
                        $rordergoods = [];
                        if ($data['status'] == 3) {
                            //出库商品
                            $rgoods = (new OrderGoods())->where('ordersn', $order['ordersn'])->select();
                            if ($rgoods) {
                                $rgoods = $rgoods->toArray();
                            }
                            //出库单数组
                            $rorder = [
                                'type' => 2,
                                'tst' => '订单出库',
                                'user_id' => $this->request->admin['id'],
                                'ordersn' => reordersn(new Lorder()),
                                'orderid' => $order['id'],
                                'remark' => '订单出库：订单号' . $order['ordersn'],
                                'total' => $order['total'],
                                'ptotal' => $order['ptotal']
                            ];
                        }
                        Db::startTrans();
                        try {
                            (new Orders())->where('id', $id)->update(['status' => $data['status']]);
                            //已经出库的取消操作要撤库并返回库存
                            if (($order['status'] >= 3 && $order['status'] <= 5) && $data['status'] <= 2) {
                                //查找当前订单入库商品
                                $lgoods = (new LorderGoods())->where('orderid', $order['id'])->select();
                                foreach ($lgoods as $good) {
                                    //加库存
                                    (new GoodsSpec())->where('id', $good['goodspecid'])->setInc('stock', $good['number']);
                                }
                                (new LorderGoods())->where('orderid', $order['id'])->delete();
                                (new Lorder())->where('orderid', $order['id'])->delete();
                            }
                            //出库的时候要增库减库存操作
                            if ($data['status'] == 3) {
                                foreach ($rgoods as $good) {
                                    $good['orderid'] = $order['id'];
                                    $good['ordersn'] = $rorder['ordersn'];
                                    unset($good['id']);
                                    //减库存
                                    (new GoodsSpec())->where('id', $good['goodspecid'])->setDec('stock', $good['number']);
                                    $rordergoods[] = $good;
                                }
                                (new Lorder())->allowfield(true)->save($rorder);
                                (new LorderGoods())->allowfield(true)->saveAll($rordergoods);
                            }
                            Db::commit();
                        } catch (\Exception $e) {
                            Db::rollback();
                            return json(['status' => 1, 'msg' =>  '操作失败，请重试' . $e->getMessage()]);
                        }
                        break;
                    }
                default:
                    # code...
                    break;
            }
            return json(['status' => 0, 'msg' =>  '操作成功']);
        } else {
            //客户列表
            $id  = $this->request->get('id/d', '0');
            $list = (new Orders())->where('id', $id)->find();
            if ($list) {
                $list['status_text'] = $list->status_text;
                $list['review_text'] = $list->review_text;
                $ordergoods = (new OrderGoods())->where(['ordersn' => $list['ordersn']])->select();
                foreach ($ordergoods as $goods) {
                    $goods['images'] = json_decode($goods['images'] ?? '', true);
                }
                $list['goods'] = $ordergoods;
                $list['images'] = json_decode($list['images'] ?? '', true);
            }
            return view(null, [
                'row' => $list
            ]);
        }
    }

    public function rkd()
    {
        $list = (new Lorder())->where(['type' => 1])->order(['id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('tst|ordersn|remark', 'like', '%' . $data['title'] . '%');
        }
        $list = $list->paginate(15);
        return view(null, [
            'list' => $list
        ]);
    }

    public function ckd()
    {
        $list = (new Lorder())->where(['type' => 2])->order(['id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('tst|ordersn|remark', 'like', '%' . $data['title'] . '%');
        }
        $list = $list->paginate(15);
        return view(null, [
            'list' => $list
        ]);
    }


    public function ckd_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
            ], [
                'goodsid.require' => '商品不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $goods = $data['goodsid'];
            $order = [
                'type' => 2,
                'tst' => '添加出库单',
                'user_id' => $this->request->admin['id'],
                'ordersn' => reordersn(new Lorder()),
                'total' => 0,
                'remark' => $data['remark'] ?? '',
                'total' => 0,
                'ptotal' => 0
            ];
            $ordergoods = [];
            foreach ($goods as $good) {
                $goodspec = (new Goods())->where('g.isdel', 1)->where('g.id', $good['id'])->alias('g')->join('GoodsSpec gs', 'gs.goodid = g.id')->field('g.*,gs.name,gs.price,gs.stock,gs.unmit,gs.starbuy,gs.id as specid')->find();
                if (!empty($goodspec) && $good['number'] > 0) {
                    $order['ptotal'] += $good['price'] * $good['number'];
                    $ordergoods[] = [
                        'ordersn' => $order['ordersn'],
                        'classid' => $goodspec['classid'],
                        'goodsid' => $goodspec['id'],
                        'goodspecid' => $goodspec['specid'],
                        'title' => $goodspec['title'],
                        'images' => $goodspec['images'] ?? '',
                        'name' => $goodspec['name'],
                        'number' =>  $good['number'],
                        'unmit' => $goodspec['unmit'],
                        'price' =>   $good['price'],
                        'total' => floor($good['number'] * $good['price'] * 100) / 100
                    ];
                }
            }
            $order['total'] = $order['ptotal'];
            if (count($ordergoods) < 1 || count($order) < 1) {
                return json(['status' => 1, 'msg' =>  '商品下架或未填写商品数量']);
            }
            Db::startTrans();
            try {
                (new Lorder())->allowfield(true)->save($order);
                (new LorderGoods())->allowfield(true)->saveAll($ordergoods);
                //减库存
                foreach ($ordergoods as $goods) {
                    (new GoodsSpec())->where('id', $goods['goodspecid'])->setDec('stock', $goods['number']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'msg' =>  '操作失败，请重试' . $e->getMessage()]);
            }
            return json(['status' => 0, 'msg' =>  '操作成功']);
        } else {
            //客户列表
            return view(null, [
                'user' => (new User())->select()
            ]);
        }
    }


    public function rkd_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
            ], [
                'goodsid.require' => '商品不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $goods = $data['goodsid'];
            $order = [
                'type' => 1,
                'tst' => '添加入库单',
                'user_id' => $this->request->admin['id'],
                'ordersn' => reordersn(new Lorder()),
                'total' => 0,
                'remark' => $data['remark'] ?? '',
                'total' => 0,
                'ptotal' => 0
            ];
            $ordergoods = [];
            foreach ($goods as $good) {
                $goodspec = (new Goods())->where('g.isdel', 1)->where('g.id', $good['id'])->alias('g')->join('GoodsSpec gs', 'gs.goodid = g.id')->field('g.*,gs.name,gs.price,gs.stock,gs.unmit,gs.starbuy,gs.id as specid')->find();
                if (!empty($goodspec) && $good['number'] > 0) {
                    $order['ptotal'] += $good['price'] * $good['number'];
                    $ordergoods[] = [
                        'ordersn' => $order['ordersn'],
                        'classid' => $goodspec['classid'],
                        'goodsid' => $goodspec['id'],
                        'goodspecid' => $goodspec['specid'],
                        'title' => $goodspec['title'],
                        'images' => $goodspec['images'] ?? '',
                        'name' => $goodspec['name'],
                        'number' =>  $good['number'],
                        'unmit' => $goodspec['unmit'],
                        'price' =>   $good['price'],
                        'total' => floor($good['number'] * $good['price'] * 100) / 100
                    ];
                }
            }
            $order['total'] = $order['ptotal'];
            if (count($ordergoods) < 1 || count($order) < 1) {
                return json(['status' => 1, 'msg' =>  '商品下架或未填写商品数量']);
            }
            Db::startTrans();
            try {
                (new Lorder())->allowfield(true)->save($order);
                (new LorderGoods())->allowfield(true)->saveAll($ordergoods);
                //减库存
                foreach ($ordergoods as $goods) {
                    (new GoodsSpec())->where('id', $goods['goodspecid'])->setInc('stock', $goods['number']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'msg' =>  '操作失败，请重试' . $e->getMessage()]);
            }
            return json(['status' => 0, 'msg' =>  '操作成功']);
        } else {
            //客户列表
            return view(null, [
                'user' => (new User())->select()
            ]);
        }
    }
}
